const { google } = require('googleapis');
const path = require('path');

const winston = require('winston');

const log = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [
        new winston.transports.File({ filename: 'log/google-sheets.log' }), // 输出到文件
        new winston.transports.Console() // 输出到控制台
    ]
});

const auth = new google.auth.GoogleAuth({
    keyFile: path.resolve(__dirname, '../google-sheets/swift-synthesis-450101-j7-08e26bb7334e.json'),
    scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});

const sheets = google.sheets({ version: 'v4', auth });

// 打印认证信息
auth.getClient().then(client => {
    console.log('Authentication successful', client);
}).catch(error => {
    console.error('Authentication failed', error);
});

let Notification;
if (process.type === 'renderer') {
    Notification = require('electron').Notification;
}

async function readRowData(spreadsheetId, range) {
    try {
        const res = await sheets.spreadsheets.values.get({
            spreadsheetId,
            range,
        });
        return res.data.values || [];
    } catch (error) {
        log.error(`Error in readRowData: ${error.stack || error}`);
        throw error;
    }
}

async function updateRowData(spreadsheetId, plmCode, rowData, range) {
    try {
        const data = await readRowData(spreadsheetId, range);
        const rowIndex = data.findIndex(row => row[5]?.includes(plmCode));

        if (rowIndex === -1) {
            throw new Error(`未找到 PLM Code: ${plmCode}`);
        }

        await sheets.spreadsheets.values.update({
            spreadsheetId,
            range: `107!A${rowIndex + 1}:Z${rowIndex + 1}`,
            valueInputOption: 'RAW',
            requestBody: {
                values: [rowData]
            }
        });

        log.info(`成功更新 ${spreadsheetId} 中的 PLM Code: ${plmCode}`);
    } catch (error) {
        log.error(`更新数据失败: ${error.stack || error}`);
        throw error;
    }
}

async function getSheetNames(spreadsheetId) {
    try {
        const response = await sheets.spreadsheets.get({
            spreadsheetId,
        });
        return response.data.sheets?.map(sheet => sheet.properties?.title || '') || [];
    } catch (error) {
        console.error('获取工作表名称失败:', error);
        throw error;
    }
}

async function readColumnData(spreadsheetId, range) {
    try {
        const res = await sheets.spreadsheets.values.get({
            spreadsheetId,
            range,
        });

        const rows = res.data.values;
        if (!rows || rows.length === 0) {
            log.info('No data found.');
            return [];
        }

        return rows.map(row => row[0]);
    } catch (error) {
        log.error(`Error in readColumnData: ${error.stack || error}`);
        throw error;
    }
}

async function updatePartialColumns(spreadsheetId, sheetName, plmCode, columnUpdates, range) {
    try {
        const data = await readRowData(spreadsheetId, range);
        const rowIndex = data.findIndex(row => row[5]?.includes(plmCode));

        if (rowIndex === -1) {
            throw new Error(`未找到 PLM Code: ${plmCode}`);
        }

        const requests = Object.entries(columnUpdates).map(([colIndex, value]) => ({
            range: `${sheetName}!${String.fromCharCode(65 + parseInt(colIndex))}${rowIndex + 1}`,
            values: [[value]]
        }));

        await sheets.spreadsheets.values.batchUpdate({
            spreadsheetId,
            requestBody: {
                data: requests,
                valueInputOption: 'RAW'
            }
        });

        log.info(`成功更新 ${spreadsheetId} 中的 PLM Code: ${plmCode}`);
    } catch (error) {
        log.error(`更新数据失败: ${error.stack || error}`);
        throw error;
    }
}

async function writeData() {
    try {
        await electronAPI.writeData();
    } catch (error) {
        log.error(`Error in write data: ${error.stack || error}`);
    } finally {
        const notification = new Notification({
            title: 'Task Finished',
            body: 'Google sheets写入结束，更多详情请查看log日志。',
        });
        notification.show();
    }
}

module.exports = {
    readRowData,
    updateRowData,
    getSheetNames,
    readColumnData,
    updatePartialColumns,
    writeData
};